﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.ApplicationPages;
using TVR.Timerjobs.Utilitys;
using TVR.Timerjobs.JobDefenitions;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Utilities;
using System.Web.UI;
using System.Reflection;

namespace TVR.Timerjobs.PagesCode
{
    public class TimerjobCreation : GlobalAdminPageBase
    {
        protected TextBox txtUrlRSSFeed;
        protected TextBox txtJobName;
        protected DropDownList ddlTimerjobTypes;
        protected Button btnCreate;

        protected DropDownList ddlPickSchedule;
        protected TextBox txtScheduleMinutelyInterval;
        protected TextBox txtScheduleHourlyInterval;
        protected TextBox txtScheduleDailyHour;
        protected TextBox txtScheduleDailyMinute;

        protected PlaceHolder PlaceHolderProperties;
        protected PlaceHolder PlaceHolderScheduleHourly;
        protected PlaceHolder PlaceHolderScheduleMinutely;
        protected PlaceHolder PlaceHolderScheduleDaily;
        protected PlaceHolder PlaceHolderSchedules;

        protected Literal ErrorMessageLiteral;

        private string namespaceTimerjobDefs = new DummyJob().GetType().Namespace;

        #region Events

        protected override void OnLoad(EventArgs e)
        {
            try
            {
                //Event hanlders
                btnCreate.Click += new EventHandler(btnCreate_Click);
                btnCreate.Attributes.Add("OnClick", "if (! confirm('Are you sure you want to create this timerjob now?')) return false;");

                //Load TimerjobTypes
                LoadTimerjobTypes();

                //Hide certain inputfields
                HideAllScheduleInput();

                //Display the scheduleinput depending on the choice in dropdownlist
                DisplaySelectedScheduleInput();

                //Display possible timerjobproperties
                DisplayTimerJobProperties();

                base.OnLoad(e);
            }
            catch (Exception ex)
            {
                ErrorMessageLiteral.Text = ex.Message.ToString();
            }
        }

        private void DisplayTimerJobProperties()
        {

            string fullName = namespaceTimerjobDefs + "." + ddlTimerjobTypes.SelectedItem.Text;
            Type jobType = Type.GetType(fullName);

            // Cycle through the properties.
            foreach (FieldInfo varProperty in jobType.GetFields())
            {
                Label lblKey = new Label();
                lblKey.Text = varProperty.Name;

                TextBox txtValue = new TextBox();
                txtValue.ID = varProperty.Name;

                PlaceHolderProperties.Controls.Add(new LiteralControl(@"<table width=""100%"" class=""ms-authoringcontrols"">"));
                PlaceHolderProperties.Controls.Add(new LiteralControl("<tr>"));
                PlaceHolderProperties.Controls.Add(new LiteralControl("<td>"));
                PlaceHolderProperties.Controls.Add(lblKey);
                PlaceHolderProperties.Controls.Add(new LiteralControl("</td>"));
                PlaceHolderProperties.Controls.Add(new LiteralControl("<td>"));
                PlaceHolderProperties.Controls.Add(txtValue);
                PlaceHolderProperties.Controls.Add(new LiteralControl("</td>"));
                PlaceHolderProperties.Controls.Add(new LiteralControl("</tr>"));
                PlaceHolderProperties.Controls.Add(new LiteralControl(@"</table>"));

            }
        }

        private void LoadTimerjobTypes()
        {
            if (!Page.IsPostBack)
            {
                //Get all classes in the same namespace (there should only be timerjobdefenitions in here)
                List<String> timerjobTypes = Utility.GetAllSPJobDefenitionClasses(namespaceTimerjobDefs);

                foreach (string type in timerjobTypes)
                {
                    ListItem item = new ListItem(type);
                    ddlTimerjobTypes.Items.Add(item);
                }
            }
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            try
            {
                //Get webapp
                SPWebApplication webApp = SPContext.Current.Web.Site.WebApplication;
                string jobName = txtJobName.Text;

                //Check if a timerjob already exists with the name
                if (!string.IsNullOrEmpty(jobName) && !Utility.TimerjobNameExists(jobName, webApp))
                {
                    //Get Schedule
                    SPSchedule schedule = GetSchedule();

                    //Register job
                    RegisterTimerjob(webApp, jobName, schedule);

                    //Set all properties for timerjobdef
                    SetPropertiesTimerjob(jobName);

                    //Redirect to operations when done
                    RedirectToOperations();
                }
                else
                {
                    ErrorMessageLiteral.Text = "The entered jobname is empty or already exists.";
                }
            }
            catch (Exception ex)
            {
                ErrorMessageLiteral.Text = ex.Message.ToString();
            }
        }

        private void SetPropertiesTimerjob(string jobDefName)
        {
            SPPropertyBag pBag = SPContext.Current.Web.Properties;

            foreach (Control c in PlaceHolderProperties.Controls)
            {
                if (c.GetType() == typeof(TextBox))
                {
                    pBag = Utility.SetPropertybagKey(pBag, jobDefName + "-" + c.ID, ((TextBox)c).Text);
                }
            }
        }


        private void RegisterTimerjob(SPWebApplication webApp, string jobName, SPSchedule schedule)
        {
           
            string fullName = namespaceTimerjobDefs + "." + ddlTimerjobTypes.SelectedItem.Text;
            object[] args = new object[2];
            args[0] = jobName;
            args[1] = webApp;

            SPJobDefinition j = (SPJobDefinition)Activator.CreateInstance(Type.GetType(fullName), args);
            j.Schedule = schedule;
            j.Update();
        }

        #endregion

        private void RedirectToOperations()
        {
            this.RedirectToOperationsPage();
        }


        #region schedule

        private void DisplaySelectedScheduleInput()
        {
            if (!string.IsNullOrEmpty(ddlPickSchedule.SelectedValue))
                PlaceHolderSchedules.FindControl(ddlPickSchedule.SelectedValue).Visible = true;
        }

        private void HideAllScheduleInput()
        {
            PlaceHolderScheduleHourly.Visible = false;
            PlaceHolderScheduleDaily.Visible = false;
            PlaceHolderScheduleMinutely.Visible = false;
        }

        private SPSchedule GetSchedule()
        {

            switch (ddlPickSchedule.SelectedValue)
            {
                case "PlaceHolderScheduleMinutely":
                    SPMinuteSchedule scheduleMin = new SPMinuteSchedule();
                    scheduleMin.BeginSecond = 0;
                    scheduleMin.EndSecond = 0;
                    int intervalMin;
                    if (int.TryParse(txtScheduleMinutelyInterval.Text, out intervalMin))
                        intervalMin = int.Parse(txtScheduleMinutelyInterval.Text);
                    else
                    {
                        throw new Exception("The interval for minutes in your timerjob schedule must be numeric");
                    }
                    scheduleMin.Interval = intervalMin;
                    return scheduleMin;
                case "PlaceHolderScheduleHourly":
                    SPHourlySchedule scheduleHour = new SPHourlySchedule();

                    int beginMin;
                    if (int.TryParse(txtScheduleHourlyInterval.Text, out beginMin))
                        beginMin = int.Parse(txtScheduleHourlyInterval.Text);
                    else
                    {
                        throw new Exception("The beginminute in your timerjob schedule must be numeric");
                    }
                    scheduleHour.BeginMinute = beginMin;
                    scheduleHour.EndMinute = beginMin;
                    return scheduleHour;
                case "PlaceHolderScheduleDaily":
                    SPDailySchedule scheduleDay = new SPDailySchedule();

                    int startHour;
                    if (int.TryParse(txtScheduleDailyHour.Text, out startHour))
                        startHour = int.Parse(txtScheduleDailyHour.Text);
                    else
                    {
                        throw new Exception("The startHour in your timerjob schedule must be numeric");
                    }

                    int startMinute;
                    if (int.TryParse(txtScheduleDailyMinute.Text, out startMinute))
                        startMinute = int.Parse(txtScheduleDailyMinute.Text);
                    else
                    {
                        throw new Exception("The hour in your timerjob schedule must be numeric");
                    }

                    scheduleDay.BeginHour = startHour;
                    scheduleDay.BeginMinute = startMinute;
                    scheduleDay.BeginSecond = 0;
                    scheduleDay.EndHour = startHour;
                    scheduleDay.EndMinute = startMinute;
                    scheduleDay.EndSecond = 0;
                    return scheduleDay;
                default:
                    //If none of the above was selected then don't change schedule
                    return null;
            }
        }

        #endregion

    }
}
